<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>阶梯计提计算器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        input:focus { outline: 2px solid #2563eb; }
        .settings-scroll { max-height: 35vh; overflow-y: auto; }
        .success-tip { color: #10b981; font-size: 0.75rem; margin: 0; animation: fadeInOut 3s ease forwards; }
        .error-tip { color: #ef4444; font-size: 0.75rem; margin: 0; }
        @keyframes fadeInOut { 0% { opacity: 0; } 20% { opacity: 1; } 80% { opacity: 1; } 100% { opacity: 0; } }
        
        .task-list-container { 
            max-height: 300px; 
            overflow-y: auto; 
            border: 1px solid #eee; 
            border-radius: 8px; 
            padding: 10px; 
            margin-top: 10px;
            background: #fff;
        }
        .task-item { padding: 12px; border-bottom: 1px solid #eee; margin-bottom: 8px; border-radius: 6px; background: #fafafa; display: flex; flex-direction: column; }
        .task-row { display: flex; justify-content: space-between; align-items: center; }
        .delete-btn { 
            background: #3498db; 
            color: white; 
            border: none; 
            padding: 6px 10px; 
            border-radius: 6px; 
            font-size: 12px; 
            cursor: pointer; 
            min-width: 70px;
            transition: all 0.3s ease;
        }
        .delete-btn.confirm {
            background: #e74c3c;
            animation: pulse 0.5s;
        }
        .delete-all-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 12px;
            border-radius: 8px;
            font-size: 16px;
            width: 100%;
            cursor: pointer;
            margin-top: 15px;
            transition: all 0.3s ease;
        }
        .delete-all-btn.confirm {
            background: #e74c3c;
            animation: pulse 0.5s;
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        .task-info { margin-bottom: 8px; font-size: 14px; }
        .task-amount { color: #e74c3c; font-weight: bold; font-size: 16px; }
        .empty { text-align: center; padding: 30px 0; color: #999; font-size: 16px; }
        .tip { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #4CAF50; color: white; padding: 12px 24px; border-radius: 8px; font-size: 16px; z-index: 1000; }
        .stats-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 20px; }
        .stat-card { background: #f8f9fa; padding: 12px; border-radius: 8px; text-align: center; }
        .stat-card p { font-size: 14px; color: #6c757d; margin-bottom: 5px; }
        .stat-card span { font-size: 16px; font-weight: bold; }
        .chart-wrapper { height: 220px; margin-top: 15px; }
        
        .date-filter-section {
            margin: 20px 0;
            padding: 15px;
            background: #f0f7ff;
            border-radius: 8px;
        }
        .date-filter-section h3 {
            font-size: 16px;
            color: #2c3e50;
            margin-bottom: 12px;
            text-align: center;
        }
        .date-filter-controls {
            display: flex;
            gap: 10px;
            margin-bottom: 12px;
        }
        .date-filter-controls input {
            flex: 1;
            padding: 10px;
            font-size: 14px;
        }
        .date-filter-result {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
        }
        
        .task-list-container::-webkit-scrollbar {
            width: 8px;
        }
        .task-list-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        .task-list-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        .task-list-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        .import-export-buttons {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        .import-export-buttons button {
            flex: 1;
            padding: 10px;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            border: none;
            transition: background-color 0.3s;
        }
        #export-btn {
            background-color: #10b981;
            color: white;
        }
        #export-btn:hover {
            background-color: #059669;
        }
        #import-btn {
            background-color: #3b82f6;
            color: white;
        }
        #import-btn:hover {
            background-color: #2563eb;
        }
        #import-file {
            display: none;
        }
    </style>
</head>
<body class="bg-gray-100 p-4">
    <div class="max-w-3xl mx-auto space-y-4">
        <div class="bg-white rounded-lg shadow">
            <div id="settings-header" class="p-3 font-bold bg-gray-50 cursor-pointer flex justify-between">
                <span>计提规则设置</span>
                <span id="settings-icon">+</span>
            </div>
            <div id="settings-content" class="p-3 hidden settings-scroll">
                <div class="flex gap-2 mb-3">
                    <div class="flex-1">
                        <label class="block text-sm font-semibold mb-1">载货保底(元)</label>
                        <input type="number" id="base-freight" value="40.00" step="0.01" min="0" class="w-full p-2 border rounded">
                    </div>
                    <div class="flex-1">
                        <label class="block text-sm font-semibold mb-1">空驶保底(元)</label>
                        <input type="number" id="base-empty" value="40.00" step="0.01" min="0" class="w-full p-2 border rounded">
                    </div>
                </div>
                <div class="flex gap-2 mb-2">
                    <button id="confirm-rule" class="px-3 py-1 bg-green-500 text-white rounded text-sm">确认当前规则</button>
                    <button id="add-rule" class="px-3 py-1 bg-blue-500 text-white rounded text-sm">添加区间</button>
                    <button id="del-rule" class="px-3 py-1 bg-red-500 text-white rounded text-sm">删除区间</button>
                </div>
                <div id="tip-container" class="mb-2"></div>
                <div class="overflow-x-auto">
                    <table class="min-w-full border-collapse text-sm">
                        <thead><tr class="bg-gray-50"><<th class="border p-1 text-left">区间结束(km)</</th><<th class="border p-1 text-left">载货单价(元/km)</</th><<th class="border p-1 text-left">空驶单价(元/km)</</th></tr></thead>
                        <tbody id="rule-table"></tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <h3 class="font-bold mb-3">单趟计提计算</h3>
            <div class="flex gap-3 mb-3">
                <div class="flex-1 border p-2 rounded"><div class="text-sm text-gray-600">载货计提</div><div id="freight-result" class="text-xl font-bold text-green-600">¥ 0.00</div></div>
                <div class="flex-1 border p-2 rounded"><div class="text-sm text-gray-600">空驶计提</div><div id="empty-result" class="text-xl font-bold text-blue-600">¥ 0.00</div></div>
            </div>
            <div>
                <label class="block text-sm font-semibold mb-1">公里数（如12.5）</label>
                <input type="number" id="distance" step="0.1" min="0" placeholder="输入公里数" class="w-full p-2 border rounded">
                <button id="calc-btn" class="mt-2 w-full py-2 bg-blue-600 text-white rounded">计算计提</button>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow">
            <div id="more-header" class="p-3 font-bold bg-gray-50 cursor-pointer flex justify-between">
                <span>更多功能</span>
                <span id="more-icon">+</span>
            </div>
            <div id="more-content" class="p-4 hidden">
                <div class="input-item mb-3">
                    <label class="block text-sm font-semibold mb-1">任务类型</label>
                    <select id="task-type" class="w-full p-2 border rounded">
                        <option value="loaded">载货任务</option>
                        <option value="empty">空驶任务</option>
                    </select>
                </div>
                <div class="input-item mb-3">
                    <label class="block text-sm font-semibold mb-1">任务日期</label>
                    <input type="date" id="task-date" class="w-full p-2 border rounded">
                </div>
                <button id="add-task-btn" class="w-full py-2 bg-green-600 text-white rounded mb-4">添加任务到列表</button>
                
                <div class="stats-grid mb-4">
                    <div class="stat-card"><p>总任务数</p><span id="total-tasks">0</span></div>
                    <div class="stat-card"><p>总收入</p><span id="total-amount">¥0.00</span></div>
                </div>
                
                <div class="mb-4">
                    <h3 class="text-sm font-semibold mb-2">每周收入</h3>
                    <div class="chart-wrapper"><canvas id="income-chart"></canvas></div>
                </div>
                <div class="date-filter-section">
                    <h3 class="text-sm font-semibold mb-2">时间筛选统计</h3>
                    <div class="date-filter-controls">
                        <input type="date" id="filter-start-date" class="p-2 border rounded">
                        <input type="date" id="filter-end-date" class="p-2 border rounded">
                    </div>
                    <div class="date-filter-result">
                        <div class="stat-card">
                            <p>筛选任务数</p>
                            <span id="filtered-task-count">0</span>
                        </div>
                        <div class="stat-card">
                            <p>筛选总收入</p>
                            <span id="filtered-income">¥0.00</span>
                        </div>
                    </div>
                </div>
                <div class="mt-4">
                    <h3 class="text-sm font-semibold mb-2">任务列表</h3>
                    <div class="task-list-container">
                        <div id="task-list" class="task-list">
                            <div class="empty">暂无任务</div>
                        </div>
                    </div>
                    <button id="delete-all-btn" class="delete-all-btn mt-3">全部删除</button>
                </div>
                
                <div class="import-export-buttons">
                    <button id="export-btn">导出数据</button>
                    <input type="file" id="import-file" accept=".json">
                    <button id="import-btn">导入数据</button>
                </div>
            </div>
        </div>
    </div>
    <script>
        const DEFAULT_SETTINGS = {
            rules: [
                { endKm: 10, freightRate: 1.6, emptyRate: 1.0 },
                { endKm: 20, freightRate: 1.5, emptyRate: 0.8 },
                { endKm: 40, freightRate: 1.2, emptyRate: 0.5 },
                { endKm: 60, freightRate: 1.0, emptyRate: 0.3 },
                { endKm: 100, freightRate: 0.8, emptyRate: 0.1 },
                { endKm: 200, freightRate: 0.6, emptyRate: 0.05 },
                { endKm: 500, freightRate: 0.3, emptyRate: 0.03 },
                { endKm: Infinity, freightRate: 0.15, emptyRate: 0.01 }
            ],
            baseFreight: 40.00, 
            baseEmpty: 40.00
        };
        
        let tempRules = [...DEFAULT_SETTINGS.rules];
        let activeRules = JSON.parse(JSON.stringify(tempRules));
        let baseFreight = DEFAULT_SETTINGS.baseFreight;
        let baseEmpty = DEFAULT_SETTINGS.baseEmpty;
        let taskData = JSON.parse(localStorage.getItem('driverTasks') || '[]');
        let chart = null;
        
        const dom = {
            settingsHeader: document.getElementById('settings-header'),
            settingsContent: document.getElementById('settings-content'),
            settingsIcon: document.getElementById('settings-icon'),
            ruleTable: document.getElementById('rule-table'),
            confirmRuleBtn: document.getElementById('confirm-rule'),
            addRuleBtn: document.getElementById('add-rule'),
            delRuleBtn: document.getElementById('del-rule'),
            tipContainer: document.getElementById('tip-container'),
            baseFreight: document.getElementById('base-freight'),
            baseEmpty: document.getElementById('base-empty'),
            distance: document.getElementById('distance'),
            calcBtn: document.getElementById('calc-btn'),
            freightResult: document.getElementById('freight-result'),
            emptyResult: document.getElementById('empty-result'),
            moreHeader: document.getElementById('more-header'),
            moreContent: document.getElementById('more-content'),
            moreIcon: document.getElementById('more-icon'),
            taskType: document.getElementById('task-type'),
            taskDate: document.getElementById('task-date'),
            addTaskBtn: document.getElementById('add-task-btn'),
            totalTasks: document.getElementById('total-tasks'),
            totalAmount: document.getElementById('total-amount'),
            incomeChart: document.getElementById('income-chart'),
            filterStartDate: document.getElementById('filter-start-date'),
            filterEndDate: document.getElementById('filter-end-date'),
            filteredTaskCount: document.getElementById('filtered-task-count'),
            filteredIncome: document.getElementById('filtered-income'),
            taskList: document.getElementById('task-list'),
            deleteAllBtn: document.getElementById('delete-all-btn'),
            exportBtn: document.getElementById('export-btn'),
            importBtn: document.getElementById('import-btn'),
            importFile: document.getElementById('import-file')
        };
        
        function parseDate(dateStr) {
            const parts = dateStr.split('-');
            if (parts.length !== 3) return new Date(NaN);
            const year = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1;
            const day = parseInt(parts[2], 10);
            return new Date(year, month, day);
        }
        
        function getWeekOfMonth(date) {
            const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
            const firstDayOfWeek = firstDay.getDay() || 7;
            const weekNumber = Math.ceil((date.getDate() + firstDayOfWeek - 1) / 7);
            return Math.min(weekNumber - 1, 3);
        }
        
        function showTip(type, text){
            dom.tipContainer.innerHTML = '';
            const tip = document.createElement('p');
            tip.className = type === 'success' ? 'success-tip' : 'error-tip';
            tip.innerHTML = `${type === 'success' ? '✅' : '⚠️'} ${text}`;
            dom.tipContainer.appendChild(tip);
            if (type === 'success') setTimeout(() => dom.tipContainer.innerHTML = '', 3000);
        }
        
        function showAdvancedTip(text) {
            const tip = document.createElement('div'); 
            tip.className = 'tip'; 
            tip.textContent = text;
            document.body.appendChild(tip); 
            setTimeout(() => tip.remove(), 2000);
        }
        
        function renderTable(){
            dom.ruleTable.innerHTML = '';
            tempRules.forEach((rule, idx) => {
                const tr = document.createElement('tr');
                tr.className = idx % 2 === 0 ? 'bg-white' : 'bg-gray-50';
                tr.innerHTML = `
                    <td class="border p-1"><input type="text" value="${rule.endKm === Infinity ? '无限' : rule.endKm}" class="w-full p-1 border rounded" oninput="updateRule(${idx}, 'endKm', this.value)"></td>
                    <td class="border p-1"><input type="number" step="0.01" min="0" value="${rule.freightRate}" class="w-full p-1 border rounded" oninput="updateRule(${idx}, 'freightRate', this.value)"></td>
                    <td class="border p-1"><input type="number" step="0.01" min="0" value="${rule.emptyRate}" class="w-full p-1 border rounded" oninput="updateRule(${idx}, 'emptyRate', this.value)"></td>
                `;
                dom.ruleTable.appendChild(tr);
            });
        }
        
        window.updateRule = function(idx, key, value){
            if (idx >= tempRules.length) return;
            if (key === 'endKm') tempRules[idx].endKm = (value === '无限' || value === '') ? Infinity : Math.max(0, parseFloat(value) || 0);
            else tempRules[idx][key] = Math.max(0, parseFloat(value) || 0);
            dom.tipContainer.innerHTML = '';
        };
        
        function checkRule(){
            const validRules = tempRules.filter(r => r.endKm !== Infinity);
            for (let i = 1; i < validRules.length; i++) if (validRules[i].endKm <= validRules[i-1].endKm) return { ok: false, tip: '区间需递增（如10→20→40）' };
            for (const r of tempRules) if (r.freightRate < 0 || r.emptyRate < 0) return { ok: false, tip: '单价不能为负数' };
            return { ok: true, tip: '新规则已生效' };
        }
        
        function calcTotal(km, rules, base){
            const validKm = isNaN(km) || km < 0 ? 0 : parseFloat(km.toFixed(1));
            if (validKm === 0) return Math.max(0, base);
            let total = 0, prevEnd = 0;
            for (const r of rules) {
                const currEnd = r.endKm;
                const segmentKm = currEnd === Infinity ? (validKm > prevEnd ? validKm - prevEnd : 0) : (validKm <= currEnd ? validKm - prevEnd : currEnd - prevEnd);
                total += segmentKm * r.freightRate;
                prevEnd = currEnd;
                if (validKm <= currEnd) break;
            }
            return Math.max(total, base);
        }
        
        const STORAGE_KEY = 'ladderCalculatorSettings';
        const TASK_STORAGE_KEY = 'driverTasks';
        
        function saveSettings(){ 
            localStorage.setItem(STORAGE_KEY, JSON.stringify({ 
                rules: activeRules, 
                baseFreight, 
                baseEmpty 
            })); 
        }
        
        function saveTasksToLocalStorage() {
            localStorage.setItem(TASK_STORAGE_KEY, JSON.stringify(taskData));
        }
        
        function loadSettings(){
            const savedSettings = localStorage.getItem(STORAGE_KEY);
            if (savedSettings) try {
                const parsed = JSON.parse(savedSettings);
                if (Array.isArray(parsed.rules) && parsed.rules.length > 0) { 
                    tempRules = parsed.rules; 
                    activeRules = JSON.parse(JSON.stringify(tempRules)); 
                }
                if (typeof parsed.baseFreight === 'number') baseFreight = parsed.baseFreight;
                if (typeof parsed.baseEmpty === 'number') baseEmpty = parsed.baseEmpty;
            } catch (e) { console.error("加载本地存储失败，使用默认设置。", e); }
            
            dom.baseFreight.value = baseFreight;
            dom.baseEmpty.value = baseEmpty;
            
            const savedTasks = localStorage.getItem(TASK_STORAGE_KEY);
            if (savedTasks) try {
                taskData = JSON.parse(savedTasks);
            } catch (e) { console.error("加载任务数据失败。", e); }
        }
        
        function initChart() {
            chart = new Chart(document.getElementById('income-chart').getContext('2d'), {
                type: 'bar',
                data: { 
                    labels: ['第1周','第2周','第3周','第4周'], 
                    datasets: [{ 
                        label: '收入', 
                        data: [0,0,0,0], 
                        backgroundColor: 'rgba(54,162,235,0.6)' 
                    }] 
                },
                options: { 
                    responsive: true, 
                    maintainAspectRatio: false, 
                    scales: { y: { beginAtZero: true } }
                }
            });
        }
        
        function calculateFilteredStats() {
            const startDate = parseDate(dom.filterStartDate.value);
            const endDate = parseDate(dom.filterEndDate.value);
            
            if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
                dom.filteredTaskCount.textContent = '0';
                dom.filteredIncome.textContent = '¥0.00';
                return;
            }
            const filteredTasks = taskData.filter(task => {
                const taskDate = parseDate(task.date);
                return taskDate >= startDate && taskDate <= endDate;
            });
            const taskCount = filteredTasks.length;
            const totalIncome = filteredTasks.reduce((sum, task) => sum + parseFloat(task.amt), 0).toFixed(2);
            dom.filteredTaskCount.textContent = taskCount;
            dom.filteredIncome.textContent = `¥${totalIncome}`;
        }
        
        function renderTaskList() {
            if (taskData.length === 0) {
                dom.taskList.innerHTML = '<div class="empty">暂无任务</div>';
                dom.deleteAllBtn.style.display = 'none';
                calculateFilteredStats();
                return;
            }
            
            dom.deleteAllBtn.style.display = 'block';
            
            dom.taskList.innerHTML = taskData.map(t => {
                return `
                    <div class="task-item">
                        <div class="task-info">${t.typeText} | ${t.date} | ${t.dist}公里</div>
                        <div class="task-row">
                            <div class="task-amount">¥${t.amt}</div>
                            <button class="delete-btn" data-id="${t.id}">删除</button>
                        </div>
                    </div>`;
            }).join('');
            calculateFilteredStats();
        }
        
        function updateStats() {
            const count = taskData.length;
            const total = taskData.reduce((sum, t) => sum + parseFloat(t.amt), 0).toFixed(2);
            dom.totalTasks.textContent = count;
            dom.totalAmount.textContent = `¥${total}`;
            const weekly = [0,0,0,0];
            const currentMonth = new Date().getMonth();
            const currentYear = new Date().getFullYear();
            
            taskData.forEach(t => {
                const taskDate = parseDate(t.date);
                if (taskDate.getMonth() === currentMonth && taskDate.getFullYear() === currentYear) {
                    const weekIndex = getWeekOfMonth(taskDate);
                    weekly[weekIndex] += parseFloat(t.amt);
                }
            });
            if (chart) {
                chart.data.datasets[0].data = weekly;
                chart.update();
            }
            calculateFilteredStats();
        }
        
        function addTask() {
            const km = parseFloat(dom.distance.value);
            if (!dom.taskDate.value || isNaN(km) || km <= 0) { 
                showAdvancedTip('请选择日期并输入有效距离！'); 
                return; 
            }
            
            const type = dom.taskType.value;
            const typeText = type === 'loaded' ? '载货任务' : '空驶任务';
            
            let amt;
            if (type === 'loaded') {
                amt = calcTotal(km, activeRules, baseFreight);
            } else {
                const emptyRules = activeRules.map(r => ({ ...r, freightRate: r.emptyRate }));
                amt = calcTotal(km, emptyRules, baseEmpty);
            }
            
            taskData.unshift({ 
                type, 
                typeText, 
                dist: km.toFixed(1), 
                amt: amt.toFixed(2), 
                date: dom.taskDate.value,
                id: Date.now().toString() 
            });
            
            saveTasksToLocalStorage();
            renderTaskList();
            updateStats();
            showAdvancedTip('任务添加成功！');
        }
        
        function deleteTask(taskId) {
            const initialLength = taskData.length;
            taskData = taskData.filter(t => t.id !== taskId);
            
            if (taskData.length !== initialLength) {
                saveTasksToLocalStorage();
                renderTaskList();
                updateStats();
            }
            
            showAdvancedTip('任务删除成功！');
        }
        
        function deleteAllTasks() {
            if (taskData.length === 0) {
                showAdvancedTip('没有任务可删除！');
                return;
            }
            
            taskData = [];
            saveTasksToLocalStorage();
            renderTaskList();
            updateStats();
            showAdvancedTip('所有任务已删除！');
        }
        
        function exportData() {
            const data = {
                settings: {
                    rules: activeRules,
                    baseFreight,
                    baseEmpty
                },
                tasks: taskData,
                exportDate: new Date().toISOString()
            };
            
            const dataStr = JSON.stringify(data, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            
            const link = document.createElement('a');
            link.href = URL.createObjectURL(dataBlob);
            link.download = `计提计算器数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            showAdvancedTip('数据导出成功！');
        }
        
        function importData(file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const data = JSON.parse(e.target.result);
                    
                    if (data.settings) {
                        if (Array.isArray(data.settings.rules) && data.settings.rules.length > 0) {
                            tempRules = data.settings.rules;
                            activeRules = JSON.parse(JSON.stringify(tempRules));
                        }
                        if (typeof data.settings.baseFreight === 'number') baseFreight = data.settings.baseFreight;
                        if (typeof data.settings.baseEmpty === 'number') baseEmpty = data.settings.baseEmpty;
                        
                        dom.baseFreight.value = baseFreight;
                        dom.baseEmpty.value = baseEmpty;
                        renderTable();
                        saveSettings();
                    }
                    
                    if (Array.isArray(data.tasks)) {
                        taskData = data.tasks;
                        saveTasksToLocalStorage();
                        renderTaskList();
                        updateStats();
                    }
                    
                    showAdvancedTip('数据导入成功！');
                } catch (error) {
                    console.error('导入数据解析失败:', error);
                    showAdvancedTip('导入失败：文件格式不正确');
                }
            };
            reader.readAsText(file);
        }
        
        function init(){ 
            loadSettings(); 
            renderTable(); 
            
            const today = new Date();
            const yyyy = today.getFullYear();
            const mm = String(today.getMonth() + 1).padStart(2, '0');
            const dd = String(today.getDate()).padStart(2, '0');
            const todayStr = `${yyyy}-${mm}-${dd}`;
            dom.taskDate.value = todayStr;
            dom.filterStartDate.value = todayStr;
            dom.filterEndDate.value = todayStr;
            
            initChart();
            renderTaskList();
            updateStats();
        }
        
        dom.settingsHeader.addEventListener('click', () => {
            const isHidden = dom.settingsContent.classList.toggle('hidden');
            dom.settingsIcon.textContent = isHidden ? '+' : '-';
        });
        
        dom.moreHeader.addEventListener('click', () => {
            const isHidden = dom.moreContent.classList.toggle('hidden');
            dom.moreIcon.textContent = isHidden ? '+' : '-';
        });
        
        dom.confirmRuleBtn.addEventListener('click', () => {
            baseFreight = Math.max(0, parseFloat(dom.baseFreight.value) || 0);
            baseEmpty = Math.max(0, parseFloat(dom.baseEmpty.value) || 0);
            const res = checkRule();
            if (res.ok) { 
                activeRules = JSON.parse(JSON.stringify(tempRules)); 
                saveSettings(); 
                showTip('success', res.tip); 
            } else {
                showTip('error', res.tip);
            }
        });
        
        dom.addRuleBtn.addEventListener('click', () => {
            const last = tempRules[tempRules.length - 1];
            const newEnd = last.endKm === Infinity ? 1000 : last.endKm + 100;
            tempRules.splice(tempRules.length - 1, 0, { endKm: newEnd, freightRate: 0, emptyRate: 0 });
            renderTable(); 
            dom.tipContainer.innerHTML = '';
        });
        
        dom.delRuleBtn.addEventListener('click', () => {
            if (tempRules.length <= 2) { 
                showTip('error', '至少保留2个区间（含"无限"）'); 
                return; 
            }
            tempRules.splice(tempRules.length - 2, 1); 
            renderTable(); 
            dom.tipContainer.innerHTML = '';
        });
        
        dom.calcBtn.addEventListener('click', () => {
            const km = parseFloat(dom.distance.value);
            const freight = calcTotal(km, activeRules, baseFreight);
            const emptyRules = activeRules.map(r => ({ ...r, freightRate: r.emptyRate }));
            const empty = calcTotal(km, emptyRules, baseEmpty);
            dom.freightResult.textContent = `¥ ${freight.toFixed(2)}`;
            dom.emptyResult.textContent = `¥ ${empty.toFixed(2)}`;
        });
        
        dom.addTaskBtn.addEventListener('click', addTask);
        
        dom.taskList.addEventListener('click', (e) => {
            if (e.target.classList.contains('delete-btn')) {
                const button = e.target;
                const taskId = button.dataset.id;
                
                if (button.classList.contains('confirm')) {
                    deleteTask(taskId);
                } else {
                    button.classList.add('confirm');
                    button.textContent = '确认删除';
                    
                    setTimeout(() => {
                        if (button.classList.contains('confirm')) {
                            button.classList.remove('confirm');
                            button.textContent = '删除';
                        }
                    }, 3000);
                }
            }
        });
        
        dom.deleteAllBtn.addEventListener('click', function() {
            const button = this;
            
            if (button.classList.contains('confirm')) {
                deleteAllTasks();
                button.classList.remove('confirm');
                button.textContent = '全部删除';
            } else {
                button.classList.add('confirm');
                button.textContent = '确认全部删除';
                
                setTimeout(() => {
                    if (button.classList.contains('confirm')) {
                        button.classList.remove('confirm');
                        button.textContent = '全部删除';
                    }
                }, 5000);
            }
        });
        dom.filterStartDate.addEventListener('change', calculateFilteredStats);
        dom.filterEndDate.addEventListener('change', calculateFilteredStats);
        
        dom.exportBtn.addEventListener('click', exportData);
        
        dom.importBtn.addEventListener('click', () => {
            dom.importFile.click();
        });
        
        dom.importFile.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                importData(e.target.files[0]);
                e.target.value = '';
            }
        });
        
        init();
    </script>
</body>
</html>
